package com.wuchaooooo.service.zjutsds.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.wuchaooooo.service.zjutsds.pojo.po.PQuestion;
import com.wuchaooooo.service.zjutsds.pojo.po.PUser;
import com.wuchaooooo.service.zjutsds.pojo.po.PUserAnswer;
import com.wuchaooooo.service.zjutsds.utils.CommonUtils;

/**
 * Created by wuchaooooo on 08/06/2017.
 */
@Repository
public class UserAnswerDAO {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserAnswerDAO.class);

    @Resource(name = "primaryJdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	public List<PUserAnswer> getQuestion() {

		String sql = "select * from " + getTable();
		RowMapper<PUserAnswer> rowMapper = new BeanPropertyRowMapper<>(PUserAnswer.class);
		try {
			return jdbcTemplate.query(sql, rowMapper);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	public PUserAnswer getQuestionByUserId(int userid) {

		String sql = "select * from " + getTable() + " where user_id = ?";
		try {

			return jdbcTemplate.queryForObject(sql, new Object[] { userid },
					new BeanPropertyRowMapper<>(PUserAnswer.class));
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	public int saveQuestionByUserId(PUserAnswer ua) {
		StringBuilder sql = new StringBuilder();
		sql.append("REPLACE INTO " + getTable() + " VALUES(:userid");
		Map<String, Object> args = new HashMap<>();
		args.put("userid", ua.getUserid());
		for (int i = 1; i <= 70; i++) {
			args.put("qc" + i, CommonUtils.getFieldValueByFieldName("qc" + i, ua));
			sql.append(", :qc" + i);
		}
		for (int i = 1; i <= 140; i++) {
			args.put("qh" + i, CommonUtils.getFieldValueByFieldName("qh" + i, ua));
			sql.append(", :qh" + i);
		}
		sql.append(")");
		try {
			NamedParameterJdbcTemplate nameJdbc = new NamedParameterJdbcTemplate(jdbcTemplate);
            LOGGER.info("SQL语句：" + sql.toString());
            LOGGER.info("参数为：" + args.toString());
			return nameJdbc.update(sql.toString(), args);
		} catch (EmptyResultDataAccessException e) {
			return 0;
		}
	}

	private String getTable() {
		return "user_answer";
	}

}
